using System;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Cors;
using Microsoft.AspNetCore.Mvc;
using System.Collections.Generic;

using CYZHAPI.Common;
using CYZHAPI.Entity;
using CYZHAPI.IRepository.IService;
using CYZHAPI.Middlewares;

using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using CYZHAPI.web.Model;
using System.IO;
using Microsoft.Extensions.Options;
using CYZHAPI.Common.Config;

namespace CYZHAPI.web.Controllers
{
     public class spiResultController : BaseController
     {

         private WebApiOption _Config;
        private ISpiResultService _spiResultService;
        public spiResultController(IOptions<WebApiOption> option,ISpiResultService spiResultService, ILogger<BaseController> logger) : base(logger)
        {
            _Config = option.Value;
            _spiResultService = spiResultService;
        }
        
        [Route("SeachByYear")]
        [HttpGet("{year}")]
        public SpiResultRenBean SeachByYear(string year)
        {
            year= year==null?"2013":year;
            string starttime=year+"-01-01";
            string endtime=year+"-12-31";
            string sWhere = "starttime > to_date('"+starttime+"','yyyy-mm-dd') and endtime < to_date('"+endtime+"','yyyy-mm-dd')";
           
            List<SpiResultModel> ListInfo = _spiResultService.GetList(sWhere);
            SpiResultRenBean renBean = new SpiResultRenBean();
            if(ListInfo != null){
                renBean.code = "200";
                renBean.message = "SPI数据查询成功";
                renBean.reList = ListInfo;
            }else{
                renBean.code = "901";
                renBean.message = "SPI数据查询失败";
                renBean.reList = null;
            }
            

            return renBean;
        }

        [Route("downLoadFile")]
        [HttpGet]
        public async Task<IActionResult> downLoadFile(string fileType,string fileid){
            
            var sWhere="id="+fileid;
            var path=_Config.Path.AscResult;
            List<SpiResultModel> ListInfo = _spiResultService.GetList(sWhere);
            if(ListInfo != null&&ListInfo.Count==1){
                SpiResultModel srm=ListInfo[0];
                
                 var addrUrl=path+"\\SPI\\"+srm.filename+"."+fileType;
                var stream = System.IO.File.OpenRead(addrUrl);
                return File(stream, "application/octet-stream", srm.filename+"."+fileType);
            }else{
                return null;
            }
           
        }
     }
}
